#include "swimmingpool.h"

SwimmingPool::SwimmingPool(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags) {
	//initialize the interface
	ui.setupUi(this);

	//set up the scene
	scene = new Scene();
	scene->lights.push_back(Light(Vector3(-20, 45, 20), Color(0.5, 0.5, 0.5), Color(0, 0, 0)));

	Quad* quad = new Quad(Vector3(0, 0, 0), Vector3(0, -1, 0), 2000, 2000);
	quad->material = Material(Color(1, 0.5, 1), Color(0.4, 0.4, 0.4), Color(0.2, 0.5, 1), 100);
	scene->objects.push_back(quad);

	scene->cameraLocation = Vector3(-20.5, 40, -45);
	scene->cameraLookAt = Vector3 (-20, 0, 10);

	//set up the timer
	timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), this, SLOT(timerDone()));

	//set up openGL
	ui.glwidget->initialize(scene);
}

SwimmingPool::~SwimmingPool() {
	delete timer;
	delete scene;
}

void SwimmingPool::mainLoop() {
	clock_t end = clock();
	float elapsed; //in seconds

	//update the time
	elapsed = (float)(end - start) / CLOCKS_PER_SEC;
	start = end;

	//update openGL
	ui.glwidget->update(elapsed, true);
}

void SwimmingPool::startAnimation() {
	start = clock();
	createTimer();
}

void SwimmingPool::stopAnimation() {
	timer->stop();
}

void SwimmingPool::createTimer() {
	timer->start(0);
}

void SwimmingPool::timerDone() {
	mainLoop();
}

void SwimmingPool::trace() {
	int size = 760;
	vector<vector<Vector3> > image;

	QImage myImage(size, size, QImage::Format_RGB32);

	rayTracer.init(scene);

	time_t begin = clock();
	rayTracer.idle(image);
	debug.writeToFile((float)(clock()-begin) / CLOCKS_PER_SEC);

	for (int x = 0; x < image.size(); x++) {
		for (int y = 0; y < image[x].size(); y++) {
			Vector3 v = image[x][y];
			QRgb value = qRgb(v.x*255, v.y*255, v.z*255);
			myImage.setPixel(x, y, value);
		}
	}
	
	myImage.save("test.bmp", "BMP");
	ui.lblPicture->setPixmap(QPixmap::fromImage(myImage));
	//myImage.save(QFileDialog::getSaveFileName(this, "Load a picture or file", QString(), "BMP"));
	int test = 5;
	
}